package com.jprocms.module.cms.service.type;

import com.jpro.framework.common.pojo.PageResult;
import com.jpro.framework.common.util.object.BeanUtils;
import com.jprocms.module.cms.controller.admin.type.vo.CmsTypePageReqVO;
import com.jprocms.module.cms.controller.admin.type.vo.CmsTypeSaveReqVO;
import com.jprocms.module.cms.dal.dataobject.type.CmsTypeDO;
import com.jprocms.module.cms.dal.mysql.type.CmsTypeMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.TYPE_NOT_EXISTS;

/**
 * 内容类型 Service 实现类
 *
 * @author jprocms
 */
@Service
@Validated
public class CmsTypeServiceImpl implements CmsTypeService {

    @Resource
    private CmsTypeMapper typeMapper;

    @Override
    public Long createType(CmsTypeSaveReqVO createReqVO) {
        // 插入
        CmsTypeDO type = BeanUtils.toBean(createReqVO, CmsTypeDO.class);
        typeMapper.insert(type);
        // 返回
        return type.getId();
    }

    @Override
    public void updateType(CmsTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateTypeExists(updateReqVO.getId());
        // 更新
        CmsTypeDO updateObj = BeanUtils.toBean(updateReqVO, CmsTypeDO.class);
        typeMapper.updateById(updateObj);
    }

    @Override
    public void deleteType(Long id) {
        // 校验存在
        validateTypeExists(id);
        // 删除
        typeMapper.deleteById(id);
    }

    private void validateTypeExists(Long id) {
        if (typeMapper.selectById(id) == null) {
            throw exception(TYPE_NOT_EXISTS);
        }
    }

    @Override
    public CmsTypeDO getType(Long id) {
        return typeMapper.selectById(id);
    }

    @Override
    public PageResult<CmsTypeDO> getTypePage(CmsTypePageReqVO pageReqVO) {
        return typeMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CmsTypeDO> getTypeList(CmsTypePageReqVO pageReqVO) {
        return typeMapper.selectList(pageReqVO);
    }
}